package com.wqr.it.ecwdr.client.souq.parser;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.wqr.it.ecwdr.client.dto.StockDto;
import com.wqr.it.ecwdr.client.dto.StockItemDto;
import com.wqr.it.ecwdr.client.util.BaseParser;
import com.wqr.it.ecwdr.client.util.PriceUtils;

@Component
public class ProductSalesInfoListParser extends BaseParser {
	private static final Logger log = LoggerFactory.getLogger("INFO");

	public void parse(StockDto stockDto, String html, String domain) {
		List<StockItemDto> itemList = null;
		// log.info(html);
		if (!StringUtils.isEmpty(html)) {
			HtmlCleaner cleaner = new HtmlCleaner();  
			TagNode root = cleaner.clean(html);
			try {
				itemList = getSalesInfoList(root, domain);
				if (itemList == null || itemList.isEmpty()) {
				//	 log.info(html);
				}
				
				//pageVO = getPageVO(root, list);
				//log.info(curPage + "/" + totalPage);
			} catch (XPatherException e) {
				log.error(e.getMessage());
			} catch (NumberFormatException e) {
				log.error(e.getMessage());
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
			}
		} else {
			itemList = new ArrayList<>(0);
		}
		stockDto.setItemList(itemList);
	}

	private List<StockItemDto> getSalesInfoList(TagNode root, String domain) throws XPatherException {
		// 获取销售信息
		List<StockItemDto> list = new ArrayList<StockItemDto>();
		Object[] tagNodes = root.evaluateXPath("//div[@id='condition-all']/div");
		if (tagNodes == null || tagNodes.length == 0) {
			tagNodes = root.evaluateXPath("//div[@id='olpOfferList']");
		} 
		if (tagNodes == null || tagNodes.length == 0) {
			log.info("tagNodes is empty ");
		} else {
			for (int i = 0; i < tagNodes.length; i++) {
				StockItemDto stockItemDto = parse((TagNode)tagNodes[i], domain);
				if (stockItemDto != null) {
					list.add(stockItemDto);
				}
			}
		}
		return list;
	}

	private StockItemDto parse(TagNode node, String domain) {
		StockItemDto stockItemDto = null;
		if (node != null) {
			try {
				stockItemDto = new StockItemDto();
						
				
				// price
				String price = getText(node, "//div[@class='larg-price']");
				if (price == null) {
					price = getText(node, "//span[@class='a-size-large a-color-price olpOfferPrice']");
				}
				if (price == null) {
					price = getText(node, "//div[@class='large-2 medium-2 small-6 columns price-field']");
				}
				if (price != null) {
					stockItemDto.setPrice(PriceUtils.parse(price));
				}
				
				// Saller
				stockItemDto.setSallerSn(getSallerSN(node, domain));
				
				
				// stock
				String stock = null;
				String sku = null;
				String itemId = null;

				List<TagNode> tagNodeList = getElementList(node, "//div[@class='large-4 medium-4 small-6 columns seller-field']/div[@class='field']");
				if (tagNodeList != null) {
					int length = tagNodeList.size();
					if (length > 0) {
						stock = tagNodeList.get(0).getText().toString();
					}
					if (length > 1) {
						sku = tagNodeList.get(1).getText().toString();
					}
					if (length > 2) {
						itemId = tagNodeList.get(2).getText().toString();
					}
				}
				
				if (stock != null) {
					stock = stock.replace("In Stock :", "").replace("available.", "").replace("available", "").trim();
					try {
						stockItemDto.setStock(Integer.parseInt(stock));
					} catch (NumberFormatException e) {
						log.info(stock + " at " + stockItemDto);
						e.printStackTrace();
					}
				}
				
				if (sku != null) {
					sku = sku.replace("SKU :", "").trim();
				}
				
				if (itemId != null) {
					itemId = itemId.replace("Item ID :", "").trim();
				}
				
				// sku
				stockItemDto.setSku(sku);
				
				// itemId
				stockItemDto.setItemId(itemId);
				
				String extendId = getAttrText(node, "//form[@class='addToCart']/input[@name='id_seller']", "value");
				stockItemDto.setExtendId(extendId);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return stockItemDto ;
	}
	
	/**
	 * 获取销售商编号 
	 * @param node
	 * @return
	 */
	private String getSallerSN(TagNode node, String domain)  {
		String sn = null;
		try {
			TagNode sallerNode = getElement(node, "//div[@class='data marb-5']/span/a");
			if (sallerNode == null) {
				sallerNode = getElement(node, "//div[@class='data marb-5']/div/h3/a");
			}
			if (sallerNode == null) {
				sallerNode = getElement(node, "//p[@class='a-spacing-mini olpSellerName']/span/a");
			}
			if (sallerNode == null) {
				sallerNode = getElement(node, "//h3[@class='a-spacing-none olpSellerName']/a");
			}
			if (sallerNode == null) {
				sallerNode = getElement(node, "//h3[@class='a-spacing-none olpSellerName']/span/a");
			}
			if (sallerNode == null) {
				sallerNode = getElement(node, "//div[@class='field seller-name']/span/a");
			}
			if (sallerNode != null) {
				String href = sallerNode.getAttributeByName("href");
				if (href != null) {
					// http://uae.souq.com/ae-en/hugenose/p/
					href = href.replace(domain + "/", "");
					if (href.indexOf("/") != -1) {
						href = href.substring(0, href.indexOf("/"));
					}
					if (href.trim().length() > 0) {
						sn = href;
					}
				}
			} else {
				sallerNode = getElement(node, "//h3[@class='a-spacing-none olpSellerName']");
				if (sallerNode == null) {
					sallerNode = getElement(node, "//p[@class='a-spacing-none olpSellerName']");
				}
				if (sallerNode != null) {
					String str = getText(sallerNode, "//span");
					if (str != null) {
						// Amazon.com
						str = str.trim();
					} else {
						str = "";
					}
					List<TagNode> list = sallerNode.getChildTagList();
					if (list.size() == 1
							|| str.indexOf("Amazon") != -1) {
						// amazon自营
						sn = "Amazon";
					}
				}
				if (sn == null) {
					log.error("Fail to get saller");
				}
			}
		} catch (XPatherException e) {
			log.error(e.getMessage());
		}
		return sn;
	}
}
